﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace 基金信息查看工具
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        #region 成员变量

        Tools T = new Tools();      //辅助功能函数对象

        string[] file;  //打开的文件名
        int index = 0;  //当前文件位置

        string[] name;
        string[] ID;    //基金代码
        float[] N1;     //份额
        float[] N2;     //总成本
        string date = "基金信息";
        string tail = "2113";

        #endregion


        #region ListView数据的输入与输出

        //从listView中获取基金信息
        private string[][] getData()
        {
            int R = listView1.Items.Count;      //行数
            int L = listView1.Columns.Count;    //列数

            ListViewItem iteam;
            string[][] data = new string[R][];
            for (int i = 0; i < R; i++)
            {
                iteam = listView1.Items[i];     //读取对应的列表项
                data[i] = new string[L];
                for (int j = 0; j < L; j++)     //读取对应列数据项
                {
                    data[i][j] = iteam.SubItems[j].Text;
                }
            }

            return data;
        }

        //将信息显示到listView中，并提取基金基础信息
        private void setData(string[][] data)
        {
            listView1.Items.Clear();
            ListViewItem iteam;
            for(int i=0; i<data.Length; i++)
            {
                //根据收益率，设置icon
                int icon = 2;
                try
                {
                    float rate = parse(data[i][9].Replace("%", ""));
                    if (rate > 0) icon = 0;
                    else if (rate < 0) icon = 1;
                } catch(Exception){}

                iteam = listView1.Items.Add(data[i][0], icon);  //基金代码
                for (int j = 1; j < data[i].Length; j++)        //添加数据到列
                {
                    iteam.SubItems.Add(data[i][j]);
                }
            }

            getBasicInfo(data); //提取基础信息
        }

        //从data中提取基本信息
        private void getBasicInfo(string[][] data)
        {
            int L = data.Length;

            ID = new string[L];
            name = new string[L];
            N1 = new float[L];
            N2 = new float[L];
            
            for (int i = 0; i < L; i++)
            {
                string[] D = data[i];

                ID[i] = D[0];
                name[i] = D[1];
                N1[i] = parse(D[2]);
                N2[i] = parse(D[5]);
            }

        }
        
        #endregion


        #region 刷新，获取在线数据，计算收益情况

        //从字符串获取数据
        private float parse(string str)
        {
            try { return float.Parse(str); }
            catch (Exception) { return 0; }
        }



        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ID == null) return;
            listView1.Items.Clear();

            this.Text = "正在统计信息中...";
            string[] info = T.getWebData(setUrl(ID));//获取基金信息

            float profitCount = 0;                  //总收益

            ListViewItem tmp;
            for (int i = 0; i < ID.Length; i++)
            {
                if (info[i].Equals("")) continue;

                string[] I = info[i].Split(',');    // 20150417,1.1164,0.52
                if(!I[0].Equals("")) date = I[0];   //基金日期

                float value = parse(I[1]);          //单位净值
                float allValue = value * N1[i];     //总市值
                float cost = N2[i] == 0 ? 0 : N2[i] / N1[i];         //单位成本
                float profit = allValue - N2[i];    //收益
                float rate = profit == 0 ? 0 : profit / N2[i] * 100; //收益率
                profitCount += profit;

                float sign = parse(I[2]);
                int icon = 2;
                if (sign > 0) icon = 0;
                else if (sign < 0) icon = 1;

                tmp = listView1.Items.Add(ID[i], icon);  //基金代码

                tmp.SubItems.Add(name[i].ToString());    //基金名称
                tmp.SubItems.Add(N1[i].ToString("F2"));  //基金份额
                tmp.SubItems.Add(cost.ToString("F4"));   //单位成本
                tmp.SubItems.Add(value.ToString("F4"));  //单位净值

                tmp.SubItems.Add(N2[i].ToString("F2"));     //总成本
                tmp.SubItems.Add(allValue.ToString("F2"));  //参考市值
                tmp.SubItems.Add(profit.ToString("F2"));    //浮动盈亏
                tmp.SubItems.Add(rate.ToString("F2") + "%");//收益率
                tmp.SubItems.Add(parse(I[2]).ToString("F2") + "%"); //涨跌幅
            }

            this.Text = date + " 总收益：" + profitCount.ToString("F2");
        }

        //打开指定的链接地址
        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string link = "http://www.howbuy.com/fund/" + listView1.SelectedItems[0].Text;
            System.Diagnostics.Process.Start(link);
        }

        //设置url地址
        private string[] setUrl(string[] ID)  // ID=519087
        {
            string[] url = new string[ID.Length];
            for (int i = 0; i < ID.Length; i++)
            {//http://static.howbuy.com/min/f=/upload/auto/script/fund/jzzs_166002_v2113.js
                //url[i] = "http://static.howbuy.com/min/f=/upload/auto/script/fund/jzzs_" + ID[i] + "_v2263.js";
                url[i] = "http://static.howbuy.com/min/f=/upload/auto/script/fund/jzzs_" + ID[i] + "_v" + tail + ".js";
            }
            return url;
        }


        //设置查询码
        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel2.Visible = true;
            textBox8.Text = tail;
        }

        //应用查询码
        private void button2_Click(object sender, EventArgs e)
        {
            panel2.Visible = false;
            tail = textBox8.Text.Trim();
        }
    
        #endregion


        #region 数据的载入与保存

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            T.dragEnter(e);
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string str = T.dragDrop(e);
            file = str.Split(';');
            showFile(0);
        }

        //显示文件信息
        private void showFile(int i)
        {
            if (file == null) return;

            //索引限定
            if (i >= file.Length) i = 0;
            else if (i < 0) i = file.Length - 1;
            index = i;

            string str = T.fileToString(file[i]); //读取文件数据
            string[] tmp = str.Split(':');      //分割标题和正文
            this.Text = tmp[0];                 //设置标题
            date = tmp[0].Split(' ')[0];        //获取当前文件日期信息

            string[][] data = T.ToArray(tmp[1]);//分割正文信息
            setData(data);                      //显示信息到ListView

            if (tmp.Length > 2)                 //每日查询码
                tail = tmp[2].Trim();  
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string[][] data = getData();    //获取界面中的数据
            string str = T.ToString(data);  //合成串
            if (str.Equals("")) return;     //若无数据，则不保存
            str = this.Text + ":" + str;    //添加总收益信息
            str += ":" + tail;              //添加查询码信息

            if (getMoney > 0) { str += ":预期收益" + getMoney.ToString("F2"); date += "- 赎回"; }
            if (useMoney > 0) { str += ":申购金额" + useMoney.ToString("F2"); date += "+ 申购"; }

            T.SaveProcess(str, date);       //保存到文件
            linkLabel1.Visible = true;      //显示已保存按钮
        }
        
        #endregion


        #region 显示基金信息的增、删、改

        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
            textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";

            textBox1.Enabled = true;
        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count  == 0) return;

            ListViewItem tmp = listView1.SelectedItems[0];
            panel1.Visible = true;
            textBox1.Text = tmp.SubItems[0].Text;
            textBox2.Text = tmp.SubItems[1].Text;
            textBox3.Text = tmp.SubItems[2].Text;
            textBox4.Text = tmp.SubItems[5].Text;

            textBox1.Enabled = false;
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int Len = listView1.SelectedItems.Count;
            for (int i = 0; i < Len; i++)
            {
                ListViewItem tmp = listView1.SelectedItems[0];
                if (tmp != null) listView1.Items.Remove(tmp);
            }

            getBasicInfo(getData()); //提取基础信息
        }

        //添加或修改项
        private void button1_Click(object sender, EventArgs e)
        {
            ListViewItem tmp;
            if (textBox1.Enabled)   //添加项
            {
                string key = textBox1.Text.Trim();
                if (key.Equals(""));
                else if (!listView1.Items.ContainsKey(key))
                {
                    tmp = listView1.Items.Add(key, 2);          //基金代码
                    tmp.SubItems.Add(textBox2.Text.Trim());     //基金名称
                    tmp.SubItems.Add(textBox3.Text.Trim());     //基金份额
                    tmp.SubItems.Add(""); tmp.SubItems.Add("");
                    tmp.SubItems.Add(textBox4.Text.Trim());     //总成本
                    tmp.SubItems.Add(""); tmp.SubItems.Add("");
                    tmp.SubItems.Add(""); tmp.SubItems.Add("");
                }
                else MessageBox.Show("基金" + key + "已存在！");
            }
            else                   //修改项
            {
                tmp = listView1.SelectedItems[0];
                tmp.SubItems[1].Text = textBox2.Text.Trim();//基金名称
                tmp.SubItems[2].Text = textBox3.Text.Trim();//基金份额
                tmp.SubItems[5].Text = textBox4.Text.Trim();//总成本
            }

            panel1.Visible = false;

            getBasicInfo(getData()); //提取基础信息
        }
        
        #endregion


        #region 辅助操作，历史数据切换、打开导出文件位置

        private void 上一个ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showFile(index - 1);
        }

        private void 下一个ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showFile(index + 1);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //选中保存的文件
            string file = System.AppDomain.CurrentDomain.BaseDirectory + @"基金信息\" + date + ".txt";
            System.Diagnostics.Process.Start("explorer.exe", "/n,/select," + file);
            linkLabel1.Visible = false;
        }

        #endregion


        #region 基金的申购与赎回

        float getMoney = 0;
        float useMoney = 0;
        private void button3_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;
            ListViewItem tmp = listView1.SelectedItems[0];
            int index = listView1.SelectedItems[0].Index;

            float all = parse(tmp.SubItems[5].Text.Trim());     //总成本
            float value = parse(tmp.SubItems[4].Text.Trim());   //单位净值
            float hold = parse(tmp.SubItems[2].Text.Trim());    //份额

            float num = parse(textBox5.Text.Trim());//输入值
            if (label5.Text.Equals("申购金额"))
            {
                all += num;             //总成本
                N2[index] += num;
                useMoney = num;
                float tmp2 = num / value * 0.985f;
                MessageBox.Show("预期份额 " + hold.ToString("F2") + "+" + tmp2.ToString("F2") + " = " + (hold + tmp2).ToString("F2"));
                hold += tmp2;            //持有份额
                N1[index] += tmp2;
            }
            else if (label5.Text.Equals("赎回份额"))
            {
                hold -= num;            //持有份额
                N1[index] -= num;
                float tmp2 = num * value * 0.995f;
                MessageBox.Show("预期收益 " + getMoney.ToString("F2") + "+" + tmp2.ToString("F2") + " = " + (getMoney+tmp2).ToString("F2"));

                getMoney += tmp2;
                //all -= tmp2;     //总成本
            }

            tmp.SubItems[2].Text = hold.ToString("F2");
            tmp.SubItems[5].Text = all.ToString("F2");

            panel3.Visible = false;
        }

        private void 申购ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            label5.Text = "申购金额";
            panel3.Visible = true;
        }

        private void 赎回ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            label5.Text = "赎回份额";
            panel3.Visible = true;
        }

        #endregion

        private void 软件更新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://git.oschina.net/scimence/FundViewTool/attach_files");
        }

    }
}



        ////从网站"http://1111.ip138.com/ic.asp"，获取本机外网ip地址信息串
        ////"<html>\r\n<head>\r\n<meta http-equiv=\"content-type\" content=\"text/html; charset=gb2312\">\r\n<title> 
        ////您的IP地址 </title>\r\n</head>\r\n<body style=\"margin:0px\"><center>您的IP是：[218.104.71.178] 来自：安徽省合肥市 联通</center></body></html>"

        ////获取外网ip地址
        //public string GetExtenalIpAddress()
        //{
        //    string IP = "未获取到外网ip";
        //    try
        //    {
        //        //从网址中获取本机ip数据
        //        System.Net.WebClient client = new System.Net.WebClient();
        //        client.Encoding = System.Text.Encoding.Default;
        //        string str = client.DownloadString("http://1111.ip138.com/ic.asp");
        //        client.Dispose();

        //        //提取外网ip数据 [218.104.71.178]
        //        int i1 = str.IndexOf("["), i2 = str.IndexOf("]");
        //        IP = str.Substring(i1 + 1, i2 - 1 - i1);
        //    }
        //    catch (Exception) { }

        //    return IP;
        //}

        ///// <summary>
        ///// 打开，开源资源链接地址
        ///// </summary>
        //private void LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        //{
        //    System.Diagnostics.Process.Start("http://git.oschina.net/scimence/fileSplit");

        //    //创建新的进程，打开指定网页
        //    //System.Diagnostics.Process process = new System.Diagnostics.Process();
        //    //process.StartInfo.FileName = "iexplore.exe";            //IE浏览器，可以更换
        //    //process.StartInfo.Arguments = "http://www.baidu.com";
        //    //process.Start();
        //}